﻿/*----------------------------------------------------------------
 * 
 * 版权所有：Copyright (C) 2013
 * 
 * 文件名：ExpressionHelper.cs
 * 文件功能描述：
 * 
 * 
 * 作 者：zhangq
 * 邮 箱：ifunnyface@outlook.com
 * 日 期：2013-01-07 16:16:52
 * 
 * 
 * 修改标识： Author
 * 修改描述： 相关描述
 * 
 * ---------------------------------------------------------------- */

using System;
using System.Linq.Expressions;

namespace Common
{

    /// <summary>
    /// 
    /// </summary>
    public class MapHelper
    {

        /// <summary>
        /// 
        /// </summary>
        public MapHelper()
        {
            // TODO:
        }

        //demo
        //MapHelper.GetMappedName<UsersDTO, Users>(u => u.UserId);
        /// <summary>
        /// 获取对应的字段名
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TKey"></typeparam>
        /// <param name="keySelector"></param>
        /// <returns></returns>
        public static string GetMemberName<TSource, TKey>(Expression<Func<TSource, TKey>> keySelector)
        {
            string fieldName = null;
            var exp = keySelector.Body as UnaryExpression;
            if (exp == null)
            {
                var body = keySelector.Body as MemberExpression;

                if (body != null)
                {
                    fieldName = body.Member.Name;
                }
            }
            else
            {
                var memberExpression = exp.Operand as MemberExpression;
                if (memberExpression != null)
                {
                    fieldName = memberExpression.Member.Name;
                }
            }
            return fieldName;
        }

    }

}